//
//  MahjongMainGameVC.m
//  Mahjong
//
//  Created by 饶首建 on 17/7/19.
//  Copyright © 2017年 com.ikamobile.com. All rights reserved.
//

#import "MahjongMainGameVC.h"
#import "MahjongLoginVC.h"

#import "DragImageView.h"
#import "GameModel.h"
#import "PatternModel.h"
#import "ActionModel.h"
#import "ResultModel.h"

#import "MahjongGameControlView.h"
#import "MahjongControlView.h"
#import "MahjongGameGangView.h"
#import "MahjongDataView.h"
#import "MahjongRecordView.h"
#import "MahjongMachineView.h"
#import "MahjongLogoutView.h"
#import "MahjongAlertView.h"
#import "ChartHeaderView.h"

#import "MahjongGameActionCell.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImage+animatedGIF.h"
#import "PopoverView.h"
#import "HWPopTool.h"

@interface MahjongMainGameVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIImageView *bgIgv;
//杠胡查
@property (strong, nonatomic) DragImageView *gangIgv;
@property (strong, nonatomic) DragImageView *huIgv;
@property (strong, nonatomic) DragImageView *chaIgv;
//高亮区
@property (weak, nonatomic) IBOutlet UIView *downLightView;
@property (weak, nonatomic) IBOutlet UIView *upLightView;
@property (weak, nonatomic) IBOutlet UIView *leftLightView;
@property (weak, nonatomic) IBOutlet UIView *rightLightView;
//拖动阴影
@property (weak, nonatomic) IBOutlet UIView *shadowView;
@property (weak, nonatomic) IBOutlet UIImageView *arrow_left;
@property (weak, nonatomic) IBOutlet UIImageView *arrow_up;
@property (weak, nonatomic) IBOutlet UIImageView *arrow_down;
@property (weak, nonatomic) IBOutlet UIImageView *arrow_right;

@property (nonatomic,assign) CGRect gangOriginalRect;
@property (nonatomic,assign) CGRect huOriginalRect;
@property (nonatomic,assign) CGRect chaOriginalRect;
//操作按钮&Label
@property (weak, nonatomic) IBOutlet UIButton *logoutBtn;
@property (weak, nonatomic) IBOutlet UIButton *dataBtn;
@property (weak, nonatomic) IBOutlet UIButton *filterBtn;
@property (weak, nonatomic) IBOutlet UIButton *createGameBtn;
@property (weak, nonatomic) IBOutlet UIButton *machineBtn;
@property (weak, nonatomic) IBOutlet UIButton *indexOfGameBtn;
@property (weak, nonatomic) IBOutlet UILabel *networkLabel;
@property (weak, nonatomic) IBOutlet UILabel *baseAndCeilingLabel;
@property (weak, nonatomic) IBOutlet UILabel *ruleLabel;
//实时流水
@property (weak, nonatomic) IBOutlet UITableView *liushuiTableView;
//frot 对家
@property (weak, nonatomic) IBOutlet UILabel *frontFirstLabel;
@property (weak, nonatomic) IBOutlet UIImageView *frontHeadImageView;
@property (weak, nonatomic) IBOutlet UILabel *frontNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *frontScoreLabel;
//left 上家
@property (weak, nonatomic) IBOutlet UILabel *leftFirstLabel;
@property (weak, nonatomic) IBOutlet UIImageView *leftHeadImageView;
@property (weak, nonatomic) IBOutlet UILabel *leftNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *leftScoreLabel;
//right 下家
@property (weak, nonatomic) IBOutlet UILabel *rightFirstLabel;
@property (weak, nonatomic) IBOutlet UIImageView *rightHeadImageView;
@property (weak, nonatomic) IBOutlet UILabel *rightNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *rightScoreLabel;
//me 自己
@property (weak, nonatomic) IBOutlet UILabel *meFirstLabel;
@property (weak, nonatomic) IBOutlet UIImageView *meHeadImageView;
@property (weak, nonatomic) IBOutlet UILabel *meNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *meScoreLabel;


@property (nonatomic,strong) NSMutableArray *gameArr;
@property (nonatomic,strong) PlayerModel *owner;
@property (nonatomic,strong) ResultModel *ownRM;
@property (nonatomic,strong) ResultModel *leftRM;
@property (nonatomic,strong) ResultModel *rightRM;
@property (nonatomic,strong) ResultModel *frontRM;
@property (nonatomic,strong) PatternModel *patternModel;
@property (nonatomic,strong) GameModel *currentGameModel;
@property (nonatomic,assign) NSInteger idxOfGame;

@property (nonatomic,assign) BOOL isFilter;
@property (nonatomic,assign) BOOL isCanEdit;
@property (nonatomic,strong) NSMutableArray *realtimeActionArr;

@property (nonatomic,assign) CGFloat modalViewW;
@property (nonatomic,assign) CGFloat modalViewH;
@property (nonatomic,strong) ChartHeaderView *chartHeaderView;


@end

static NSString *kMahjongGameActionCell = @"kMahjongGameActionCell";

@implementation MahjongMainGameVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initUI];
}

- (void)initData{
    _owner = [[PlayerModel alloc]init];
    _owner.playerId = [PlayerModel ownerInstance].playerId;
    _owner.playerName = [PlayerModel ownerInstance].playerName;
    _gameArr = [NSMutableArray new];
    _realtimeActionArr = [NSMutableArray new];
    _isCanEdit = YES;
}

- (void)initUI{
    
    _createGameBtn.enabled = NO;
    
    _modalViewW = SWidth() * 4/5;//modal 宽度
    _modalViewH = SHeight() * 4/5;//modal 高度
    
    NSMutableArray *tmp = [NSMutableArray new];
    [tmp addObjectsFromArray:_matchModel.rules];
    if (![tmp containsObject:@"自摸加番"]) {
        [tmp addObject:@"自摸加底"];
    }
    _ruleLabel.text = NSStringFormat(@"牌局规则:%@",[tmp componentsJoinedByString:@","]);
    _baseAndCeilingLabel.text = NSStringFormat(@"底:%ld 限番:%ld",_matchModel.base,_matchModel.ceiling);
    if (_matchModel.ceiling == 20) {
        _baseAndCeilingLabel.text = NSStringFormat(@"底:%ld 限番:%@",_matchModel.base,@"不限");
    }    
    
    _gangIgv = [[DragImageView alloc]initWithFrame:CGRectMake(202, 315, 138, 120)];
    _gangIgv.image = UIImageWithName(@"icon_gang_btn");
    _gangIgv.userInteractionEnabled = YES;
    [self.view addSubview:_gangIgv];
    _huIgv = [[DragImageView alloc]initWithFrame:CGRectMake(361, 316, 131, 118)];
    _huIgv.image = UIImageWithName(@"icon_hu_btn");
    _huIgv.userInteractionEnabled = YES;
    [self.view addSubview:_huIgv];
    _chaIgv = [[DragImageView alloc]initWithFrame:CGRectMake(307, 448, 80, 74)];
    _chaIgv.image = UIImageWithName(@"icon_cha_btn");
    _chaIgv.userInteractionEnabled = YES;
    [self.view addSubview:_chaIgv];
    
    _gangOriginalRect = _gangIgv.frame;
    _huOriginalRect = _huIgv.frame;
    _chaOriginalRect = _chaIgv.frame;
    
    [_liushuiTableView registerNib:[UINib nibWithNibName:NSStringFromClass([MahjongGameActionCell class]) bundle:nil] forCellReuseIdentifier:kMahjongGameActionCell];
    _liushuiTableView.tableFooterView = [UIView new];
}


/**
 更新界面数据：1.进入界面（newGame，loadGame）2.收到action 3.选择某一局
 */
- (void)updateData{
    //更新玩家状态
    [self updatePlayerStatus];
    //更新新局按钮状态
    [self limitCreateBtn];
    //更新实时流水 （未考虑流水过滤状态）
    [_realtimeActionArr removeAllObjects];
    if (_isFilter) {
        [_realtimeActionArr addObjectsFromArray:[self getActionAboutMe]];
    }else{
        [_realtimeActionArr addObjectsFromArray:_currentGameModel.actionArr];
    }
    [_liushuiTableView reloadData];
    if (_realtimeActionArr.count) {
        [_liushuiTableView scrollToRow:_realtimeActionArr.count-1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    //更新第几局
    [_indexOfGameBtn setTitle:NSStringFormat(@"第%ld局",_idxOfGame + 1) forState:UIControlStateNormal];
    //是否可操作，历史局不能修改
//    [self enableControl:[_currentGameModel isEqual:_gameArr.lastObject]];
}

#pragma mark - 拖动 [杠胡查]
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    
    if ([touch.view isEqual:_gangIgv]||[touch.view isEqual:_huIgv]||[touch.view isEqual:_chaIgv]) {
        _shadowView.backgroundColor = [UIColor colorWithRGB:000000 alpha:0.5];
        _shadowView.hidden = NO;
        _arrow_left.hidden = NO;
        _arrow_right.hidden = NO;
        _arrow_up.hidden = NO;
        _arrow_down.hidden = NO;

        if (!_arrow_left.image) {
            NSURL *url = [[NSBundle mainBundle] URLForResource:@"arrow_left_test" withExtension:@"gif"];
            _arrow_left.image = [UIImage animatedImageWithAnimatedGIFURL:url];
            url = [[NSBundle mainBundle] URLForResource:@"arrow_right_test" withExtension:@"gif"];
            _arrow_right.image = [UIImage animatedImageWithAnimatedGIFURL:url];
            url = [[NSBundle mainBundle] URLForResource:@"arrow_up_test" withExtension:@"gif"];
            _arrow_up.image = [UIImage animatedImageWithAnimatedGIFURL:url];
            url = [[NSBundle mainBundle] URLForResource:@"arrow_down_test" withExtension:@"gif"];
            _arrow_down.image = [UIImage animatedImageWithAnimatedGIFURL:url];
        }
        
        [self.view bringSubviewToFront:_shadowView];
        [self.view bringSubviewToFront:_arrow_left];
        [self.view bringSubviewToFront:_arrow_right];
        [self.view bringSubviewToFront:_arrow_up];
        [self.view bringSubviewToFront:_arrow_down];
        [self.view bringSubviewToFront:touch.view];
    }
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if ([touch.view isEqual:_gangIgv]||[touch.view isEqual:_huIgv]||[touch.view isEqual:_chaIgv]) {
        [self.view sendSubviewToBack:_downLightView];
        [self.view sendSubviewToBack:_upLightView];
        [self.view sendSubviewToBack:_leftLightView];
        [self.view sendSubviewToBack:_rightLightView];
        [self.view sendSubviewToBack:_bgIgv];
        
        if (CGRectIntersectsRect(_downLightView.frame, touch.view.frame)) {
            [self.view bringSubviewToFront:_downLightView];
        }else if (CGRectIntersectsRect(_upLightView.frame, touch.view.frame)) {
            [self.view bringSubviewToFront:_upLightView];
        }else if (CGRectIntersectsRect(_leftLightView.frame, touch.view.frame)) {
            [self.view bringSubviewToFront:_leftLightView];
        }else if (CGRectIntersectsRect(_rightLightView.frame, touch.view.frame)) {
            [self.view bringSubviewToFront:_rightLightView];
        }
        
        [self.view bringSubviewToFront:_arrow_left];
        [self.view bringSubviewToFront:_arrow_right];
        [self.view bringSubviewToFront:_arrow_up];
        [self.view bringSubviewToFront:_arrow_down];
        [self.view bringSubviewToFront:touch.view];
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if ([touch.view isEqual:_gangIgv]||[touch.view isEqual:_huIgv]||[touch.view isEqual:_chaIgv]) {
        _shadowView.hidden = YES;
        _arrow_left.hidden = YES;
        _arrow_right.hidden = YES;
        _arrow_up.hidden = YES;
        _arrow_down.hidden = YES;
        //弹框
        if (CGRectIntersectsRect(touch.view.frame, _downLightView.frame)
            ||CGRectIntersectsRect(touch.view.frame, _upLightView.frame)
            ||CGRectIntersectsRect(touch.view.frame, _leftLightView.frame)
            ||CGRectIntersectsRect(touch.view.frame, _rightLightView.frame)) {
            
            NSMutableArray *selectedPlayer = [NSMutableArray new];
            BOOL isZhigang = YES;
            if (CGRectIntersectsRect(touch.view.frame, _downLightView.frame)) {
                //自己
                [selectedPlayer addObjectsFromArray:[self leftPlayers]];
                isZhigang = NO;
            }else if (CGRectIntersectsRect(touch.view.frame, _upLightView.frame)) {
                //对家
                [selectedPlayer addObject:_frontRM.playerModel];
            }else if (CGRectIntersectsRect(touch.view.frame, _leftLightView.frame)) {
                //上家
                [selectedPlayer addObject:_leftRM.playerModel];
            }else if (CGRectIntersectsRect(touch.view.frame, _rightLightView.frame)) {
                //下家
                [selectedPlayer addObject:_rightRM.playerModel];
            }
            
            if ([touch.view isEqual:_gangIgv]) {
                _gangIgv.alpha = 0;
#pragma mark - 杠
                MahjongGameGangView *view = [MahjongGameGangView mahjongGameGangView];
                view.selectedPlayerArr = selectedPlayer;
                view.isZhigang = isZhigang;
                view.gameModel = _currentGameModel;
                view.owner = _owner;
                view.matchModel = _matchModel;
                [view configData];
                [self showModalWithView:view];
            }else if ([touch.view isEqual:_huIgv]){
                _huIgv.alpha = 0;
#pragma mark - 胡
                MahjongGameControlView *view = [MahjongGameControlView mahjongGameControlView];
                view.selectedPlayerArr = selectedPlayer;
                view.gameModel = _currentGameModel;
                view.controlType = ControlTypeHu;
                view.owner = _owner;
                view.patternModel = _patternModel;
                view.matchModel = _matchModel;
                [view configData];
                [self showModalWithView:view];
            }else if ([touch.view isEqual:_chaIgv]){
                _chaIgv.alpha = 0;
#pragma mark - 查
                MahjongGameControlView *view = [MahjongGameControlView mahjongGameControlView];
                view.selectedPlayerArr = selectedPlayer;
                view.gameModel = _currentGameModel;
                view.controlType = ControlTypeCha;
                view.owner = _owner;
                view.patternModel = _patternModel;
                view.matchModel = _matchModel;
                [view configData];
                [self showModalWithView:view];
            }
            
            [UIView animateWithDuration:0.3 animations:^{
                _gangIgv.frame = _gangOriginalRect;
                _huIgv.frame = _huOriginalRect;
                _chaIgv.frame = _chaOriginalRect;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.1 animations:^{
                    _gangIgv.alpha = 1;
                    _huIgv.alpha = 1;
                    _chaIgv.alpha = 1;
                }];
            }];
        }
    }
    [UIView animateWithDuration:0.2 animations:^{
        _gangIgv.frame = _gangOriginalRect;
        _huIgv.frame = _huOriginalRect;
        _chaIgv.frame = _chaOriginalRect;
    } completion:^(BOOL finished) {}];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _gangIgv.frame = _gangOriginalRect;
    _huIgv.frame = _huOriginalRect;
    _chaIgv.frame = _chaOriginalRect;
}

#pragma mark - socket通知
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectCallBack) name:NOTIFICATION_CONNECTED_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(errorCallBack) name:NOTIFICATION_ERROR_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(disConnectCallBack) name:NOTIFICATION_DISCONNECTED_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newGameCallBack:) name:NOTIFICATION_NEWGAME_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(actionCallBack:) name:NOTIFICATION_ACTION_CALLBACK object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(matchLeaveCallBack:) name:NOTIFICATION_MATCH_LEAVE_CALLBACK object:nil];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [PatternModel loadPatternDataSuccess:^(id model) {
        _patternModel = model;
    } fail:^(NSString *errorStr) {}];
    
    [self loadGames];
}

#pragma mark - socket通知:GameCallBackDelegate
- (void)connectCallBack{
    _networkLabel.text = @"网络正常";
    _networkLabel.textColor = UIColorHex(7BDBFF);
    [self loadGames];
}

- (void)errorCallBack{
    _networkLabel.text = @"连接出错";
    _networkLabel.textColor = UIColorHex(F15A5A);
}

- (void)disConnectCallBack{
    _networkLabel.text = @"连接已断开";
    _networkLabel.textColor = UIColorHex(F15A5A);
}

- (void)newGameCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    data = [NSDictionary recursionResultJson4NullclassToNullstring:data];
    GameModel *mm = [GameModel gameModelPushParse:data];
    [_gameArr addObject:mm];
    _currentGameModel = [_gameArr lastObject];
    _idxOfGame = _gameArr.count - 1;
    [self updateData];
}

- (void)actionCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    data = [NSDictionary recursionResultJson4NullclassToNullstring:data];
    GameModel *returnGameModel = [GameModel gameModelPushParse:data];
    for (int i=0;i<_gameArr.count;i++) {
        GameModel *gm = _gameArr[i];
        if ([returnGameModel.gameId isEqualToString:gm.gameId]) {
            [_gameArr replaceObjectAtIndex:i withObject:returnGameModel];
            break;
        }
    }
    _currentGameModel = _gameArr[_idxOfGame];
    [self updateData];
}

- (void)matchLeaveCallBack:(NSNotification *)notification{
    NSDictionary *data = notification.object;
    data = [NSDictionary recursionResultJson4NullclassToNullstring:data];
    //禁止操作
    [self enableControl:NO];
    
    MahjongAlertView *view = [MahjongAlertView mahjongAlertView];
    view.textLabel.text = NSStringFormat(@"%@退出了\n牌局自动终止",data[@"player"][@"name"]);
    [self showModalWithView:view];
}

#pragma mark - private method
- (void)enableControl:(BOOL)flag{
    _gangIgv.userInteractionEnabled = flag;
    _huIgv.userInteractionEnabled = flag;
    _chaIgv.userInteractionEnabled = flag;
    _isCanEdit = flag;
}

- (void)showModalWithView:(UIView*)view{
    view.layer.cornerRadius = 10.f;
    view.layer.masksToBounds = YES;
    [HWPopTool sharedInstance].shadeBackgroundType = ShadeBackgroundTypeGradient;
    [HWPopTool sharedInstance].closeButtonType = ButtonPositionTypeNone;
    [[HWPopTool sharedInstance] showWithPresentView:view animated:NO];
}

- (void)limitCreateBtn{
    //判断谁可以开新局：1，先胡 2，分最高
    GameModel *gm = _gameArr.lastObject;
    ActionModel *tmpAm;
    for (ActionModel *am in gm.actionArr) {
        if ([am.actionType isEqualToString:@"胡"]) {
            tmpAm = am;
            break;
        }
    }
    if ([tmpAm.owner.playerId isEqual:_owner.playerId]) {
        _createGameBtn.enabled = YES;
    }else{
        _createGameBtn.enabled = NO;
    }
    
    
    if (!tmpAm) {
        NSInteger tmp = 0;
        ResultModel *tmpRm = gm.resultArr.firstObject;
        for (ResultModel *rm in gm.resultArr) {
            if (rm.score > tmp) {
                tmp = rm.score;
                tmpRm = rm;
            }
        }
        if ([tmpRm.playerModel.playerId isEqual:_owner.playerId]) {
            _createGameBtn.enabled = YES;
        }else{
            _createGameBtn.enabled = NO;
        }
    }
}

- (void)loadGames{
    [GameModel gamesOfMatch:_matchModel.matchId success:^(id array) {
        [_gameArr removeAllObjects];
        [_gameArr addObjectsFromArray:array];
        _currentGameModel = [_gameArr lastObject];
        _idxOfGame = _gameArr.count - 1;
        
        [self updateData];
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)newGame{
    NSString *url = [BASE_URL stringByAppendingPathComponent:NSStringFormat(@"Matches/%@/games",_matchModel.matchId)];
    NSDictionary *param = @{};
    [HttpUtil sendRequestURL:url method:POST param:param success:^(id response) {
    } fail:^(NSString *errorStr) {
        [Hud hudText:errorStr inView:self.view];
    }];
}

- (void)updatePlayerStatus{
    ResultModel *eastRM,*southRM,*westRM,*northRM,*ownRM;
    for (ResultModel *rm in _currentGameModel.resultArr) {
        if ([rm.playerModel.playerId isEqualToString:_owner.playerId]) {
            ownRM = rm;
        }
        switch (rm.playerModel.sitType) {
            case SitPositionTypeEast:
                eastRM = rm;
                break;
            case SitPositionTypeSouth:
                southRM = rm;
                break;
            case SitPositionTypeWest:
                westRM = rm;
                break;
            case SitPositionTypeNorth:
                northRM = rm;
                break;
            default:
                break;
        }
    }
    
    SitPositionType type = [[NSUserDefaults standardUserDefaults]integerForKey:NSUSERDEFAULTS_KEY_SITPOSITION];
    switch (type) {
        case SitPositionTypeSouth:
            _ownRM = ownRM;
            //left 西
            _leftRM = westRM;
            //right 东
            _rightRM = eastRM;
            //front 北
            _frontRM = northRM;
            break;
        case SitPositionTypeWest:
            _ownRM = ownRM;
            //left 北
            _leftRM = northRM;
            //right 南
            _rightRM = southRM;
            //front 东
            _frontRM = eastRM;
            break;
        case SitPositionTypeNorth:
            _ownRM = ownRM;
            //left 东
            _leftRM = eastRM;
            //right 西
            _rightRM = westRM;
            //front 南
            _frontRM = southRM;
            break;
        case SitPositionTypeEast:
            _ownRM = ownRM;
            //left 南
            _leftRM = southRM;
            //right 北
            _rightRM = northRM;
            //front 西
            _frontRM = westRM;
            break;
            
        default:
            break;
    }
    
    //own
    [self setUserInfo:_meHeadImageView name:_meNameLabel firstName:_meFirstLabel score:_meScoreLabel data:_ownRM];
    //left
    [self setUserInfo:_leftHeadImageView name:_leftNameLabel firstName:_leftFirstLabel score:_leftScoreLabel data:_leftRM];
    //right
    [self setUserInfo:_rightHeadImageView name:_rightNameLabel firstName:_rightFirstLabel score:_rightScoreLabel data:_rightRM];
    //front
    [self setUserInfo:_frontHeadImageView name:_frontNameLabel firstName:_frontFirstLabel score:_frontScoreLabel data:_frontRM];
}

/**
 设置用户状态
 @param headIgv logo
 @param nameLabel 昵称
 @param firstLabel 昵称第一个字
 @param scoreLabel 得分
 @param rm resultModel数据
 */
- (void)setUserInfo:(UIImageView *)headIgv name:(UILabel *)nameLabel firstName:(UILabel*)firstLabel score:(UILabel *)scoreLabel data:(ResultModel*)rm{
    UIImage *defaultHeadImage = [UIImage imageWithColor:UIColorHex(E9F1F4)size:headIgv.frame.size];
    if (rm.playerModel.avatar.length) {
        [headIgv sd_setImageWithURL:[NSURL URLWithString:rm.playerModel.avatar] placeholderImage:defaultHeadImage];
        firstLabel.text = @"";
    }else{
        firstLabel.text = [rm.playerModel.playerName substringToIndex:1];
        headIgv.image = defaultHeadImage;
    }
    nameLabel.text = rm.playerModel.playerName;
    if (rm.score > 0) {
        scoreLabel.textColor = UIColorHex(F15A5A);
        scoreLabel.text = NSStringFormat(@"+%ld",rm.score);
    }else if (rm.score == 0){
        scoreLabel.textColor = UIColorHex(9B9B9B);
        scoreLabel.text = @"0";
    }else{
        scoreLabel.textColor = UIColorHex(519B00);
        scoreLabel.text = NSStringFormat(@"%ld",rm.score);
    }
}

#pragma mark - Actions

- (IBAction)filterAction:(id)sender {
    _isFilter = !_isFilter;
    [_realtimeActionArr removeAllObjects];
    if (_isFilter) {
        [_filterBtn setImage:UIImageWithName(@"game_selected") forState:UIControlStateNormal];
        [_realtimeActionArr addObjectsFromArray:[self getActionAboutMe]];
    }else{
        [_filterBtn setImage:UIImageWithName(@"game_un_selected") forState:UIControlStateNormal];
        [_realtimeActionArr addObjectsFromArray:_currentGameModel.actionArr];
    }
    [_liushuiTableView reloadData];
    if (_realtimeActionArr.count) {
        [_liushuiTableView scrollToRow:_realtimeActionArr.count-1 inSection:0 atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

- (IBAction)logoutAction:(id)sender {
    MahjongLogoutView *mahjongLogoutView = [MahjongLogoutView mahjongLogoutView];
    mahjongLogoutView.matchModel = _matchModel;
    mahjongLogoutView.gameArr = _gameArr;
    mahjongLogoutView.owner = _owner;
    mahjongLogoutView.gameModel = _gameArr.lastObject;
    mahjongLogoutView.logoutTapBlock = ^(){
        NSString *url = NSStringFormat(@"%@/Matches/%@/users/%@/leave",BASE_URL,_matchModel.matchId,_owner.playerId);
        [HttpUtil sendRequestURL:url method:POST param:@{} success:^(id response) {
            [[HWPopTool sharedInstance] closeWithBlcok:^{
                UIViewController *vc =self.presentingViewController;
                while (![vc isKindOfClass:[MahjongLoginVC class]]) {
                    vc = vc.presentingViewController;
                }
                [vc dismissViewControllerAnimated:YES completion:^{}];
            }];
        } fail:^(NSString *errorStr) {
            [Hud hudText:errorStr inView:self.view];
        }];
    };
    
    [self showModalWithView:mahjongLogoutView];
}

- (IBAction)dataAction:(id)sender {
    MahjongDataView *dataView = [MahjongDataView mahjongDataView];
    if (!_chartHeaderView) {
        _chartHeaderView = [[ChartHeaderView alloc]initWithFrame:CGRectMake(0, 0, dataView.dataContainerView.frame.size.width, dataView.dataContainerView.frame.size.height) gameArr:_gameArr matchModel:_matchModel];
    }
    [_chartHeaderView updateChartGameArr:_gameArr matchModel:_matchModel];
    [dataView.dataContainerView addSubview:_chartHeaderView];
    [self showModalWithView:dataView];
}

- (IBAction)createAction:(id)sender {
    MahjongMachineView *view = [MahjongMachineView mahjongMachineView];
    view.openOnce = YES;
    [self showModalWithView:view];
    [self newGame];
}

- (IBAction)machineAction:(id)sender {
    MahjongMachineView *view = [MahjongMachineView mahjongMachineView];
    [self showModalWithView:view];
}

- (IBAction)selectGameAction:(id)sender {
    NSMutableArray *actionsArr = [NSMutableArray new];
    for (NSInteger i=_gameArr.count; i>0; i--) {
        PopoverAction *action = [PopoverAction actionWithImage:nil title:NSStringFormat(@"第 %ld 局",i) handler:^(PopoverAction *action) {
            NSString *idx = [action.title substringWithRange:NSMakeRange(2, action.title.length - 4)];
            _currentGameModel = _gameArr[idx.integerValue-1];
            _idxOfGame = idx.integerValue - 1;
            [self updateData];
        }];
        [actionsArr addObject:action];
    }
    PopoverView *popoverView = [PopoverView popoverView];
    popoverView.style = PopoverViewStyleDark;
    [popoverView showToPoint:CGPointMake(_indexOfGameBtn.centerX, CGRectGetMaxY(_indexOfGameBtn.frame)) withActions:actionsArr];
    
}

- (NSArray*)leftPlayers{
    if ([_matchModel.rules containsObject:@"血流成河"]) {
        return _matchModel.others;
    }else{
        //已胡玩家
        NSMutableArray *gonePlayerIdArr = [NSMutableArray new];
        for (ActionModel *am in _currentGameModel.actionArr) {
            if ([am.actionType isEqualToString:@"胡"]) {
                [gonePlayerIdArr addObject:am.owner.playerId];
            }
        }
        //未胡玩家
        NSMutableArray *leftPlayerArr = [NSMutableArray new];
        for (PlayerModel *pm in _matchModel.others) {
            if (![gonePlayerIdArr containsObject:pm.playerId]) {
                [leftPlayerArr addObject:pm];
            }
        }
        return leftPlayerArr;
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _realtimeActionArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MahjongGameActionCell *cell = [tableView dequeueReusableCellWithIdentifier:kMahjongGameActionCell forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    ActionModel *am = _realtimeActionArr[indexPath.row];
    cell.owner = _owner;
    cell.onlyMe = _isFilter;
    cell.actionModel = am;
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ActionModel *am = _realtimeActionArr[indexPath.row];
    return MAX(44, [MahjongGameActionCell height:am owner:_isFilter?_owner:nil isSelf:[am.owner.playerId isEqualToString:_owner.playerId]]);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!_isCanEdit) {
        return;
    }
    ActionModel *am = _realtimeActionArr[indexPath.row];
    if (![am.owner.playerId isEqual:_owner.playerId]) {
        return;
    }
    MahjongControlView *view = [MahjongControlView mahjongControlView];
    view.matchModel = _matchModel;
    view.gameModel = _currentGameModel;
    view.playersArr = _matchModel.others;
    view.owner = _owner;
    view.isEditAction = YES;
    view.actionModel = am;
    
    view.selectedPlayerArr = [NSMutableArray arrayWithArray: am.targetsArr];
    view.selectedAttributeArr = [NSMutableArray arrayWithArray:am.attributesArr];
    view.controlType = [am.actionType isEqualToString:@"杠"]?ControlTypeGang:[am.actionType isEqualToString:@"胡"]?ControlTypeHu:ControlTypeCha;
    
    NSMutableArray *tmp = [NSMutableArray new];
    if ([am.actionType isEqualToString:@"杠"]) {
        [tmp addObjectsFromArray:_patternModel.gangPatternArr];
    }else if ([am.actionType isEqualToString:@"胡"]) {
        [tmp addObjectsFromArray:_patternModel.huPatternArr];
        [tmp addObjectsFromArray:_matchModel.optionalArr];
    }else{
        [tmp addObjectsFromArray:_patternModel.chaPatternArr];
        for (NSString *str in _matchModel.optionalArr) {
            if ([_patternModel.optionalChaPatternArr containsObject:str]) {
                [tmp addObject:str];
            }
        }
    }
    view.dataArr = tmp;
    if ([am.actionType isEqualToString:@"杠"]) {
        view.collectionView.contentInset = UIEdgeInsetsMake(100, 0, 0, 0);
    }
    [self showModalWithView:view];
}

- (NSArray *)getActionAboutMe{
    //获取与自己相关的action
    NSMutableArray *actionArr = [NSMutableArray new];
    [actionArr addObjectsFromArray:_currentGameModel.actionArr];
    for (ActionModel *am in _currentGameModel.actionArr) {
        BOOL flag = NO;
        if ([am.owner.playerId isEqualToString:_owner.playerId]) {
            flag = YES;
        }
        for (PlayerModel *pm in am.targetsArr) {
            if ([pm.playerId isEqualToString:_owner.playerId]) {
                flag = YES;
                break;
            }
        }
        for (PlayerModel *pm in am.caguaArr) {//擦挂
            if ([pm.playerId isEqualToString:_owner.playerId]) {
                flag = YES;
                break;
            }
        }
        if ([am.transferedTo.playerId isEqualToString:_owner.playerId]) {//转雨
            flag = YES;
        }
        if (!flag) {
            [actionArr removeObject:am];
        }
    }
    return actionArr;
}

- (void)layoutBtnWithBtn:(UIButton *)button{
    button.titleLabel.backgroundColor = button.backgroundColor;
    button.imageView.backgroundColor = button.backgroundColor;
    
    CGSize titleSize = button.titleLabel.bounds.size;
    CGSize imageSize = button.imageView.bounds.size;
    //文字左移
    button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, 0.0, imageSize.width);
    //图片右移
    button.imageEdgeInsets = UIEdgeInsetsMake(0.0, titleSize.width, 0.0, -titleSize.width);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
